<?php

namespace App\Http\Controllers\BG;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;


use Illuminate\Support\Facades\DB;
use Cache;
use Validator;
use Carbon\Carbon;
use function GuzzleHttp\json_encode;
use  \GatewayWorker\Lib\Gateway;

use  App\Models\Moment;
use  App\Models\PhoneCopy;
use  App\Models\Weixin;

class MomentController extends Controller
{
    public function list(Request $request)
    {
        $input = Input::only('page','limit','str','type');
        $validator = Validator::make($input, [        
            'str' => 'nullable',
            'type' => 'nullable',
            'page' => 'required',
            'limit' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->returnError([],401,'参数错误');
        }
        $moment = Moment::leftJoin('t_weixin', 't_weixin.uid', '=', 't_moment.uid')
            ->leftJoin('t_phone', 't_weixin.uid', '=', 't_phone.wechat_uid')
            ->leftJoin('t_user', 't_user.id', '=', 't_phone.user_id')
            ->whereRaw('t_moment.uid=t_moment.friendUid');
        if(isset($input['str'])){
            $moment->where('t_weixin.uid',$input['str'])->orwhere('t_weixin.nickname',$input['str']); 
        }
        if(isset($input['type'])){
            $moment->where('type',$input['type']); 
        }
        $page = $input['page'];
        $limit = $input['limit'];
        $count =  $moment->count();
        $data = $moment
            ->select('t_weixin.small_head_url','t_weixin.sex','t_user.name as user_name','t_weixin.nickname','t_moment.id','t_moment.type','t_moment.content','t_moment.uid','t_moment.friendUid','t_moment.createTime','t_moment.shareUrl','t_moment.medias','shareTitle','send_status')
            ->offset(($page-1)*$limit)
            ->limit($limit)
            ->orderBy('t_moment.id','desc')
            ->get();
        foreach ($data as $key => $value) {
            $temp = [];
            if($value['type']=='15'){
                $temp['video_url'] = $value['shareUrl'];
                $source = json_decode($value['medias'],true);
                if($source&&is_array($source)){
                    $temp['graph'] = $source[0];
                }else{
                    $temp['graph'] = '';
                }
            }
            if($value['type']=='1'){
                $temp = json_decode($value['medias'],true);
            }
            if($value['type']=='3'){
                $source = json_decode($value['medias'],true);
                if($source&&is_array($source)){
                    $temp['graph'] = $source[0];
                }else{
                    $temp['graph'] = '';
                }
                $temp['share_url'] = $value['shareUrl'];
                $temp['share_title'] = $value['shareTitle'];
                 
            }
            $data[$key]['source']  = $temp;
        }
        $fin['count'] = $count;
        $fin['data'] = $data;
        return $this->returnOk($fin);
    }

    public function delete()
    {
        $input = Input::only('id');
        $validator = Validator::make($input, [   
            'id'      => 'required',
        ]);
        if ($validator->fails()) {
            return $this->returnError([],401,'参数错误');
        }
       
        $where['id'] = $input['id'];
        $exist = Moment::where($where)->first();
        if($exist){
            $exist->delete();
        }else{
            return $this->returnError([],409,'不存在');
        }
        return $this->returnOk();
    }

    public function create()
    {
        $input = Input::only('uids', 'content','url','graph','type');
        $validator = Validator::make($input, [        
            'uids' => 'required|array',
            'content' => 'nullable',
            'url' => 'nullable',
            'graph' => 'nullable',
            'type' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->returnError([],401,'参数错误');
        }
        $temp = [];
        $temp['type'] = $data['type'] = $input['type'];
        $uids = $input['uids'];
        $temp['content'] = $data['ext']['content'] = isset($input['content'])?$input['content']:'';
        switch ($input['type']) {
            case '1':
                $temp['medias'] = json_encode($input['graph']);
                $data['ext']['images'] = $input['graph'];
                break;
            case '2':
                break;
            case '3':
                $temp['shareUrl'] = $input['url'];
                $data['ext']['url'] = $input['url'];
                break;
            case '15':
                $temp['shareUrl'] = $data['ext']['url'] = $input['url'];
                break;
        }
        $this->saveData($temp,$uids);
        $this->sendMomentToWechat($data,$uids);
        return $this->returnOk();
    }

    protected function sendMomentToWechat($data,$uids)
    {
        foreach ($uids as $key => $value) {
            $weixin = Weixin::where('id',$value)->first();
            $new_message = array(
                'type' => 'SEND_MSG_MOMENT',
                'data' => $data
            );
            if($weixin->phone_client_id&&Gateway::isOnline($weixin->phone_client_id)){
                Gateway::sendToClient($weixin->phone_client_id, json_encode($new_message));
            }
        }
        return true;
    }

    protected function saveData($data,$uids)
    {
        foreach ($uids as $key => $value) {
            $weixin = Weixin::where('id',$value)->first();
            $data['uid'] = $weixin['uid'];
            $data['friendUid'] = $weixin['uid'];
            $data['send_status'] = 1;
            $data['createTime'] = time();
            Moment::create($data);
        }
        return true;
    }
}


